package com.Lubaichen.Wiki.service;

import com.Lubaichen.Wiki.Pojo.Ebook;
import com.Lubaichen.Wiki.Pojo.EbookExample;
import com.Lubaichen.Wiki.mapper.EbookMapper;
import com.Lubaichen.Wiki.req.EbookQueryReq;
import com.Lubaichen.Wiki.req.EbookSaveReq;
import com.Lubaichen.Wiki.resp.EbookQueryResp;
import com.Lubaichen.Wiki.resp.PageResp;
import com.Lubaichen.Wiki.utils.CopyUtil;
import com.Lubaichen.Wiki.utils.SnowFlake;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import com.github.pagehelper.PageHelper;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Lubaichen
 * @date 2022年02月28日 22:18
 */
@Service
public class EbookService {

    private static final Logger LOG = LoggerFactory.getLogger(EbookService.class);
    // @Resource :JDK自带的注解，可以取代@Autowired
    @Autowired
    private EbookMapper ebookMapper;

    @Resource
    private SnowFlake snowFlake;

    public PageResp<EbookQueryResp> list(EbookQueryReq req) {
        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria();// Criteria ： 相当于where条件
        if (!ObjectUtils.isEmpty(req.getName())) {
            criteria.andNameLike("%" + req.getName() + "%");
        }
        if (!ObjectUtils.isEmpty(req.getCategoryId2())) {
            criteria.andCategory2IdEqualTo(req.getCategoryId2());
        }
        // PageHelper只对第一条sql语句生效，如果后面还有sql，那么后面这句sql就没有分页效果。
        PageHelper.startPage(req.getPage(), req.getSize());
        List<Ebook> ebooks = ebookMapper.selectByExample(ebookExample);
        PageInfo<Ebook> pageInfo = new PageInfo<>(ebooks);
        LOG.info("总页数:{}", (pageInfo.getPages()));
        LOG.info("总行数:{}", (pageInfo.getTotal()));
        PageResp<EbookQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(CopyUtil.copyList(ebooks, EbookQueryResp.class));
        return pageResp;
    }


    public void save(EbookSaveReq req) {
        Ebook ebook = CopyUtil.copy(req, Ebook.class);
        if (!ObjectUtils.isEmpty(req.getId())) { // 如果传来的req有id值，那么只进行更新。
            ebookMapper.updateByPrimaryKey(ebook);
        } else { // 如果没有就插入
            ebook.setId(snowFlake.nextId()); // 雪花算法生成id
            ebookMapper.insert(ebook);
        }
    }


    public void deleteEbookById(Long id) {
        if (!ObjectUtils.isEmpty(id)) {
            ebookMapper.deleteByPrimaryKey(id);
        }
    }
}
